﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Runtime.InteropServices;
using System.IO;
using System.Text.RegularExpressions;

namespace Cc.Inet
{
    public class InetCommon
    {
       

       

        /// <summary>
        /// 获取本地ip地址,优先取内网ip
        /// </summary>
        public static String GetLocalIp()
        {
            String[] Ips = GetLocalIpAddresses();

            foreach (String ip in Ips) if (ip.StartsWith("10.80.")) return ip;
            foreach (String ip in Ips) if (ip.Contains(".")) return ip;

            return "127.0.0.1";
        }

        /// <summary>
        /// 获取本地ip地址。多个ip
        /// </summary>
        public static String[] GetLocalIpAddresses()
        {
            string hostName = Dns.GetHostName();                    //获取主机名称  
            IPAddress[] addresses = Dns.GetHostAddresses(hostName); //解析主机IP地址  

            string[] IP = new string[addresses.Length];             //转换为字符串形式  
            for (int i = 0; i < addresses.Length; i++) IP[i] = addresses[i].ToString();
            return IP;
        }
        public static string GetExternalIP( out string errmsg)
        {
            //可用的查询外网地址的网站，可添加到此
            string[] urls = new string[] {
                "http://ip.tool.chinaz.com/",
            "http://www.net.cn/static/customercare/yourip.asp"
            };//验证过可用的地址， 2021-4-9
            string ip = "";
            errmsg = "No External IP";
            foreach (var url in urls)
            {
                try
                {
                    string html = HttpGet(url, "utf-8");
                    Match m = Regex.Match(html, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
                    if (m.Success)
                    {
                        ip = m.Value;
                        errmsg = "success";
                        break;
                    }
                }
                catch (Exception ex)
                {
                    errmsg = ex.Message;
                }
            }
            return ip;
        }

        private static string HttpGet(string url, string encoding)
        {
            string result = string.Empty;
            Encoding encode = System.Text.Encoding.GetEncoding(encoding); //设置编码
                                                                          //获取HttpWebRequest对象
            HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
            wbRequest.Method = "GET";
            wbRequest.Timeout = 1000;
            wbRequest.UseDefaultCredentials = true;
            //设置用户代理
            wbRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36";
            //获取返回流
            HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
            using (Stream responseStream = wbResponse.GetResponseStream())
            {
                //读取返回流
                using (StreamReader sReader = new StreamReader(responseStream, encode))
                {
                    result = sReader.ReadToEnd();
                }
            }
           
            return result;
        }
        [DllImport("wininet.dll")]
        
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);


        /// <summary>
        /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败 
        /// </summary>
        /// <param name="flags">描述字，接收网络连接状态描述内容</param>
        /// <returns></returns>
        public static bool IsConnectInternet(out int flags)
        {
            flags = 0;
            return InternetGetConnectedState(flags, 0);
        }


    }

}

